/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.DCclient.servlet;

import fr.DCclient.models.BrowseCompetenceModel;

import fr.DCclient.utils.AuthManager;
import fr.annuaireComp.clientUtils.CompetenceModel;
import fr.annuaireComp.clientUtils.DomaineModel;
import fr.annuaireComp.clientUtils.SavoirModel;
import fr.annuaireComp.entities.Competence;
import fr.annuaireComp.entities.DomaineCompetence;
import fr.annuaireComp.entities.SavoirCompetence;
import fr.annuaireComp.sessions.CompetencesManager;
import java.io.IOException;

import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author MiniK
 */
@WebServlet(name = "browse", urlPatterns = {"/browse"})
public class browse extends HttpServlet {
    
    @EJB
    private CompetencesManager compMan;

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //   processRequest(request, response);
        if (!AuthManager.logUser(request, response)) {
            return;
        }
        try {
            String action = request.getParameter("action");
            if (action != null) {
                if (action.equals("compinfos")) {
                    String id = request.getParameter("id");
                    Competence comp = compMan.getCompetence(Integer.parseInt(id));
                    CompetenceModel compdata = CompetenceModel.buildCompetenceModel(comp);
                    request.setAttribute("compinfosdata", compdata);
                    request.getRequestDispatcher("/WEB-INF/p_compinfos.jsp").forward(request, response);
                }
                
                
                
            } else {
                List<Competence> competences = compMan.listCompetences();
                List<DomaineCompetence> domaines = compMan.listDomaines();
                List<SavoirCompetence> savoirs = compMan.listSavoirs();
                
                BrowseCompetenceModel competencesModel = new BrowseCompetenceModel();
                
                for (SavoirCompetence savoir : savoirs) {
                    SavoirModel s = new SavoirModel(
                            savoir.getIdsavoirCompetence().toString(),
                            savoir.getLibelle());
                    competencesModel.savoirs.add(s);
                }
                
                for (DomaineCompetence domaine : domaines) {
                    DomaineModel d = new DomaineModel(domaine.getIddomaineCompetence().toString(), domaine.getLibelle());
                    competencesModel.domaines.add(d);
                }
                
                competencesModel.competencesTree = (CompetenceModel.buildCompetenceModelFromList(competences));
                
                request.setAttribute("competencesdata", competencesModel);
                
                request.getRequestDispatcher("/WEB-INF/browse.jsp").forward(request, response);
            }
        } catch (Exception ex) {
          
            request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
            String action = request.getParameter("action");
            if (action != null) {
                if (action.equals("edit")) {
                    
                    String id = request.getParameter("id");
                    Competence comp = compMan.getCompetence(Integer.parseInt(id));
                    String competenceAttribute = request.getParameter("element_id").trim();
                    String update_value = request.getParameter("update_value").trim();
                    String original_html = request.getParameter("original_html").trim();
                    try {
                        if (competenceAttribute.equals("ci_domaine")) {
                            comp.setDomaineCompetence(new DomaineCompetence(Integer.parseInt(update_value)));
                        }
                        
                        if (competenceAttribute.equals("ci_savoir")) {
                            comp.setSavoirCompetence(new SavoirCompetence(Integer.parseInt(update_value)));
                        }
                        
                        if (competenceAttribute.equals("ci_libelle")) {
                            comp.setLibelle(update_value);
                            
                        }
                        
                        if (competenceAttribute.equals("ci_idmere")) {
                            Competence compMere = null;
                            if (!update_value.isEmpty()) {
                                compMere = new Competence(Integer.parseInt(update_value));
                            }
                            comp.setCompetenceMere(compMere);
                        }
                        
                        
                        
                        compMan.editCompetence(comp);
                    } catch (Exception ex) {
                        response.getWriter().println(original_html);
                    }
                    response.getWriter().println(update_value);
                    
                }
                if (action.equals("delete")) {
                    Integer id = Integer.parseInt(request.getParameter("id"));                   
                    compMan.deleteCompetence(id);
                  
                    response.sendRedirect("browse");
                    
                }
            } else {
                
                String type = request.getParameter("type");
                String libelle;
                if (type.equals("domaine")) {
                    libelle = request.getParameter("libelle");
                    
                    if (libelle != null) {
                        
                        compMan.addDomaine(libelle.trim());
                        request.setAttribute("infomsg", "Le Domaine de compétence \"" + libelle + "\" a été créé");
                    }
                }
                
                if (type.equals("savoir")) {
                    
                    libelle = request.getParameter("libelle");
                    
                    if (libelle != null) {
                        
                        compMan.addSavoir(libelle.trim());
                        request.setAttribute("infomsg", "Le Savoir \"" + libelle + "\" a été créé");
                    }
                }
                
                if (type.equals("competence")) {
                    libelle = request.getParameter("libelle");
                    String savoir = request.getParameter("savoir");
                    String domaine = request.getParameter("domaine");
                    String competenceMere = request.getParameter("competencesMere");
                    
                    if (savoir != null && domaine != null) {
                        Integer domaineId = Integer.parseInt(domaine);
                        Integer savoirId = Integer.parseInt(savoir);
                        Integer competenceMereId = null;
                        try {
                            competenceMereId = Integer.parseInt(competenceMere);
                        } catch (Exception ex) {
                        }
                        compMan.addCompetence(libelle, savoirId, domaineId, competenceMereId);
                        
                    }
                    
                }
                response.sendRedirect("browse");//.forward(request, response);
            }
        } catch (Exception ex) {
            //  System.out.println(ex.getMessage());
            request.setAttribute("errormsg", "Impossible d'effectuer l'action demandée");
            request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
        }
        
        
        
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
